{% extends 'base/base.html' %}



{% block title %}
美食库
{% endblock %}


{% block main %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>食物库</h2>
    <div>
        <a href="{% url 'main:add_food' %}" class="btn btn-primary">添加新食物</a>
        <a href="{% url 'main:index' %}" class="btn btn-outline-secondary">返回首页</a>
    </div>
</div>

<!-- 筛选和搜索 -->
<div class="card mb-4">
    <div class="card-body">
        <form method="get" id="searchForm">
            <div class="row">
                <div class="col-md-4">
                    <div class="input-group">
                        <select class="form-select" name="category" onchange="this.form.submit()">
                            <option value="">所有类别</option>
                            {% for category in categories %}
                            <option value="{{ category.id }}"
                                    {% if selected_category == category.id|stringformat:"s" %}selected{% endif %}>
                                {{ category.name }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="input-group position-relative">
                        <input type="text" class="form-control" name="search" id="searchInput" 
                               placeholder="搜索食物... (支持中文、拼音、简拼)" 
                               value="{{ search_keyword }}"
                               autocomplete="off">
                        <button class="btn btn-outline-primary" type="submit">
                            <i class="fas fa-search">搜索</i>
                        </button>
                        <!-- 搜索建议下拉框 -->
                        <div id="searchSuggestions" class="position-absolute w-100 bg-white border rounded shadow-lg" 
                             style="top: 100%; z-index: 1000; display: none; max-height: 300px; overflow-y: auto;">
                        </div>
                    </div>
                    <div class="form-text">
                        支持中文名称、拼音全拼、拼音简拼搜索
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="d-grid">
                        <button type="button" class="btn btn-outline-secondary" onclick="clearSearch()">
                            <i class="fas fa-times me-1"></i>重置
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 搜索结果提示 -->
{% if search_keyword %}
<div class="alert alert-info">
    <i class="fas fa-search me-2"></i>
    搜索关键词: <strong>"{{ search_keyword }}"</strong>
    共找到 <strong>{{ foods.count }}</strong> 个结果
    <a href="{% url 'main:food_library' %}" class="btn btn-sm btn-outline-primary ms-2">清除搜索</a>
</div>
{% endif %}

{% if foods %}
    <div class="row">
        {% for food in foods %}
        <div class="col-md-6 col-lg-4 mb-4">
            <div class="card h-100 food-card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h5 class="card-title">{{ food.name }}</h5>
                        <span class="badge bg-secondary">{{ food.category.name }}</span>
                    </div>

                    {% if food.description %}
                    <p class="card-text">{{ food.description|truncatewords:15 }}</p>
                    {% endif %}

                    {% if food.tags %}
                    <div class="mb-2">
                        {% for tag in food.tags.split %}
                        <span class="badge bg-light text-dark me-1">{{ tag }}</span>
                        {% endfor %}
                    </div>
                    {% endif %}

                    {% if food.tags.all %}
                    <div class="mb-2">
                        {% for tag in food.tags.all %}
                        <span class="badge me-1 mb-1" style="background-color: {{ tag.color }};">
                            {{ tag.name }}
                        </span>
                        {% endfor %}
                    </div>
                    {% endif %}

                    <div class="mt-auto">
                        <small class="text-muted">添加于 {{ food.created_at|date:"Y-m-d" }}</small>
                    </div>
                </div>
                <div class="card-footer bg-transparent">
                    <button type="button" class="btn btn-sm btn-outline-info" data-bs-toggle="modal"
                            data-bs-target="#foodDetailModal" data-food-id="{{ food.id }}">
                        查看详情
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-warning"
                            onclick="suggestFood({{ food.id }})">
                        推荐这个
                    </button>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- 分页 -->
    {% if is_paginated %}
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if selected_category %}&category={{ selected_category }}{% endif %}">上一页</a>
            </li>
            {% endif %}

            {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                <li class="page-item active">
                    <a class="page-link" href="#">{{ num }}</a>
                </li>
                {% else %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ num }}{% if selected_category %}&category={{ selected_category }}{% endif %}">{{ num }}</a>
                </li>
                {% endif %}
            {% endfor %}

            {% if page_obj.has_next %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if selected_category %}&category={{ selected_category }}{% endif %}">下一页</a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}
{% else %}
    <div class="text-center py-5">
        <div class="mb-4">
            <i class="fas fa-utensils fa-4x text-muted"></i>
        </div>
        <h4 class="text-muted">食物库为空</h4>
        <p class="text-muted">还没有添加任何食物到食物库中。</p>
        <a href="{% url 'main:add_food' %}" class="btn btn-primary">添加第一个食物</a>
    </div>
{% endif %}

<!-- Food Detail Modal -->
<div class="modal fade" id="foodDetailModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">食物详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="foodDetailModalBody">
                <!-- Content will be loaded via AJAX -->
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block js %}
<script>
// 实时搜索建议功能
let searchTimeout;
const searchInput = document.getElementById('searchInput');
const searchSuggestions = document.getElementById('searchSuggestions');

searchInput.addEventListener('input', function() {
    const query = this.value.trim();
    
    // 清除之前的定时器
    clearTimeout(searchTimeout);
    
    // 如果输入为空，隐藏建议框
    if (query === '') {
        searchSuggestions.style.display = 'none';
        return;
    }
    
    // 延迟搜索，避免频繁请求
    searchTimeout = setTimeout(() => {
        fetchSearchSuggestions(query);
    }, 300);
});

// 获取搜索建议
function fetchSearchSuggestions(query) {
    fetch(`{% url 'main:food_search_api' %}?q=${encodeURIComponent(query)}`)
        .then(response => response.json())
        .then(data => {
            displaySuggestions(data.results);
        })
        .catch(error => {
            console.error('搜索建议获取失败:', error);
        });
}

// 显示搜索建议
function displaySuggestions(results) {
    const suggestionsDiv = searchSuggestions;
    
    if (results.length === 0) {
        suggestionsDiv.innerHTML = '<div class="p-3 text-muted">没有找到相关食物</div>';
        suggestionsDiv.style.display = 'block';
        return;
    }
    
    let html = '';
    results.forEach(food => {
        html += `
            <div class="suggestion-item p-3 border-bottom" onclick="selectSuggestion('${food.name}')" 
                 style="cursor: pointer; transition: background-color 0.2s;">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="fw-bold">${food.name}</div>
                        <small class="text-muted">${food.category}</small>
                    </div>
                </div>
                ${food.description ? `<div class="text-muted small mt-1">${food.description}</div>` : ''}
            </div>
        `;
    });
    
    suggestionsDiv.innerHTML = html;
    suggestionsDiv.style.display = 'block';
    
    // 添加悬停效果
    const items = suggestionsDiv.querySelectorAll('.suggestion-item');
    items.forEach(item => {
        item.addEventListener('mouseenter', function() {
            this.style.backgroundColor = '#f8f9fa';
        });
        item.addEventListener('mouseleave', function() {
            this.style.backgroundColor = '';
        });
    });
}

// 选择建议项
function selectSuggestion(foodName) {
    searchInput.value = foodName;
    searchSuggestions.style.display = 'none';
    document.getElementById('searchForm').submit();
}

// 清除搜索
function clearSearch() {
    window.location.href = "{% url 'main:food_library' %}";
}

// 点击其他地方时隐藏建议框
document.addEventListener('click', function(event) {
    if (!searchInput.contains(event.target) && !searchSuggestions.contains(event.target)) {
        searchSuggestions.style.display = 'none';
    }
});

// 食物详情模态框
var foodDetailModal = document.getElementById('foodDetailModal')
foodDetailModal.addEventListener('show.bs.modal', function (event) {
    var button = event.relatedTarget
    var foodId = button.getAttribute('data-food-id')

    document.getElementById('foodDetailModalBody').innerHTML = `
        <div class="text-center">
            <div class="spinner-border" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载食物详情...</p>
        </div>
    `;

    // 通过AJAX获取食物详情
    fetch(`/food-detail/${foodId}/`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('foodDetailModalBody').innerHTML = `
                <h6>${data.name}</h6>
                <p><strong>类别:</strong> ${data.category}</p>
                <p><strong>描述:</strong> ${data.description}</p>
                <p><strong>标签:</strong> ${data.tags}</p>
            `;
        })
        .catch(error => {
            document.getElementById('foodDetailModalBody').innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    加载失败，请稍后重试
                </div>
            `;
        });
});

// 推荐食物功能
function suggestFood(foodId) {
    if (confirm('将此食物添加到今日推荐?')) {
        // 重定向到首页并预选这个食物
        window.location.href = "{% url 'main:index' %}?suggest=" + foodId;
    }
}

// 键盘导航支持
searchInput.addEventListener('keydown', function(e) {
    const suggestions = searchSuggestions.querySelectorAll('.suggestion-item');
    let currentIndex = -1;
    
    // 找到当前选中的项
    suggestions.forEach((item, index) => {
        if (item.style.backgroundColor === 'rgb(248, 249, 250)') {
            currentIndex = index;
        }
    });
    
    if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (currentIndex < suggestions.length - 1) {
            if (currentIndex >= 0) {
                suggestions[currentIndex].style.backgroundColor = '';
            }
            currentIndex++;
            suggestions[currentIndex].style.backgroundColor = '#f8f9fa';
        }
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (currentIndex > 0) {
            suggestions[currentIndex].style.backgroundColor = '';
            currentIndex--;
            suggestions[currentIndex].style.backgroundColor = '#f8f9fa';
        }
    } else if (e.key === 'Enter') {
        e.preventDefault();
        if (currentIndex >= 0 && suggestions[currentIndex]) {
            selectSuggestion(suggestions[currentIndex].querySelector('.fw-bold').textContent);
        } else {
            document.getElementById('searchForm').submit();
        }
    } else if (e.key === 'Escape') {
        searchSuggestions.style.display = 'none';
    }
});
</script>

{% endblock %}